package com.manager.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.manager.constants.Constants;

/**
 * 生成Token
 *
 * @author zhou
 * @date 2021/07/11 16:40
 **/
public class TonkenUtils {

  /**
   * 生成Token
   * @param id
   * @return
   */
  public static String getToken(Long id) {
    JWTCreator.Builder builder = JWT.create();
    return builder.withClaim("userId", id)
      .sign(Algorithm.HMAC256(Constants.MEMBER_TOKEN_KEYPREFIX));
  }

  /**
   * 解析token
   * @param code
   * @return id
   */
  public static Long decode(String code) {
    JWTVerifier build = JWT.require(Algorithm.HMAC256(Constants.MEMBER_TOKEN_KEYPREFIX)).build();
    DecodedJWT decode = build.verify(code);
    return decode.getClaim("userId").asLong();
  }

}
